package com.gomo;

import org.ksoap2.serialization.SoapObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.View;
import android.widget.EditText;
import android.widget.ToggleButton;

//import com.gomo.R;

public class LoginActivity extends Activity {
	private EditText txtLoginEmail;
	private EditText txtLoginPin;
	private ToggleButton btnToggle;
	AlertDialog alertDialog;
	private SharedPreferences appSettings;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		setUI();
	}

	public void buttonLoginSigninClick(View view) {

		// Intent myIntent = new Intent(getBaseContext(), CcListActivity.class);
		// startActivityForResult(myIntent, 0);

		if (isValidate()) {
			setRemember();
			new ParseXmlTask().execute();
		}
	}

	private boolean isValidate() {
		if (!GlobalService.isOnline(this)) {
			GlobalService
					.MessageBox("Not or limited internet connection", this);
			return false;
		}

		String hostUrl = getString(R.string.service_url);
		if (!GlobalService.isHostAvailable1(hostUrl)) {
			GlobalService.MessageBox(
					"System is temporarily down, please try again later", this);
			return false;
		}
		return true;
	}

	public void buttonToggleClicked(View view) {
		setRemember();
	}

	private void setRemember() {
		SharedPreferences.Editor prefEditor = appSettings.edit();
		if (btnToggle.isChecked()) {
			prefEditor.putString("userEmail", txtLoginEmail.getText()
					.toString());
			prefEditor.putString("userPin", txtLoginPin.getText().toString());
			prefEditor.putBoolean("isRemembered", true);
		} else {
			prefEditor.putString("userEmail", txtLoginEmail.getText()
					.toString());
			prefEditor.putString("userPin", txtLoginPin.getText().toString());
			prefEditor.putBoolean("isRemembered", false);
		}
		prefEditor.commit();
	}

	private void setUI() {
		txtLoginEmail = (EditText) findViewById(R.id.login_text_email);
		txtLoginPin = (EditText) findViewById(R.id.login_text_pin);
		btnToggle = (ToggleButton) findViewById(R.id.login_button_toggle);
		appSettings = getSharedPreferences("GomoAppPreferences", MODE_PRIVATE);
		Boolean isRemembered = appSettings.getBoolean("isRemembered", false);
		btnToggle.setChecked(isRemembered);
		if (isRemembered) {
			String userEmail = appSettings.getString("userEmail", "")
					.toString();
			String userPin = appSettings.getString("userPin", "").toString();

			txtLoginEmail.setText(userEmail);
			txtLoginPin.setText(userPin);
		}

		createDialogMessage();
	}

	private String processService() {
		SoapService ss = new SoapService();
		String soap_method_name = getString(R.string.method_login);
		String soap_namespace = getString(R.string.service_namespace);
		String soap_url = getString(R.string.service_url);
		String soap_action = soap_namespace + soap_method_name;
		String android_id = Secure.getString(getBaseContext()
				.getContentResolver(), Secure.ANDROID_ID);
		SoapObject soap_object_request = new SoapObject(soap_namespace,
				soap_method_name);
		soap_object_request.addProperty("EmailId", txtLoginEmail.getText()
				.toString());
		soap_object_request.addProperty("PinCode", txtLoginPin.getText()
				.toString());
		SoapObject soap_object_response = ss.parseWebService(soap_action,
				soap_url, soap_object_request);
		SoapObject recordsArray = (SoapObject) soap_object_response
				.getProperty(0);
		String soapresultid = recordsArray.getProperty("ID").toString();
		String soapresultmsg = recordsArray.getProperty("Message").toString();
		return soapresultid + "|" + soapresultmsg;
	}

	private void createDialogMessage() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("").setCancelable(false)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		alertDialog = builder.create();
	}

	class ParseXmlTask extends AsyncTask<Void, Void, String> {
		private final ProgressDialog dialog = new ProgressDialog(
				LoginActivity.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Loggin in...");
			this.dialog.show();
		}

		protected String doInBackground(Void... unused) {
			return processService();
		}

		protected void onPostExecute(String soapresultmsg) {
			if (this.dialog.isShowing())
				this.dialog.dismiss();
			String[] arrString = GlobalService.splitString(soapresultmsg, "|");
			String id = arrString[0];
			String message = arrString[1];
			if (id.equalsIgnoreCase("0")) {
				alertDialog.setMessage(message);
				alertDialog.show();
			} else {
				GlobalService.setUserId(id);
				GlobalService.setUserEmail(txtLoginEmail.getText().toString());
				GlobalService.setUserPicCode(txtLoginPin.getText().toString());
				Intent myIntent = new Intent(getBaseContext(),
						HomeActivity.class);
				finish();
				startActivityForResult(myIntent, 0);
			}
		}
	}
}